<?php

namespace app\common\library\token\driver;

use app\common\library\token\Driver;

class Cache extends Driver
{
    protected $options = [
        'prefix'      => 'user_token',
        'expire'     => 2592000,
        'connection' => [],
        'userprefix'  => 'up:'
    ];
    /**
     * 构造函数.
     *
     * @param array $options 参数
     */
    public function __construct($options = [])
    {
        if (! empty($options)) {
            $this->options = array_merge($this->options, $options);
        }

    }
    public function set($token, $user_id, $expire = 0){
        if (is_null($expire)) {
            $expire = $this->options['expire'];
        }
        if ($expire instanceof \DateTime) {
            $expire = $expire->getTimestamp() - time();
        }
        $token = $this->getEncryptedToken($token);
        $key = $this->options['prefix'].$token;
        $userprefix = $this->options['userprefix'].$user_id;
        \think\facade\Cache::set($userprefix, $key);
        return \think\facade\Cache::set($key, $user_id, $expire);
    }

    /**
     * 获取Token内的信息.
     *
     * @param string $token
     *
     * @return array
     */
    public function get($token){
        $key = $this->getEncryptedToken($token);
        $key = $this->options['prefix'].$key;
        $value = \think\facade\Cache::get($key);
        if (is_null($value) || false === $value) {
            return [];
        }
        $expire = $this->options['expire'] < 0 ? 365 * 86400 : $this->options['expire'];
        $expiretime = time() + $expire;
        $result = ['token' => $token, 'user_id' => $value, 'expiretime' => $expiretime, 'expires_in' => $expire];
        return $result;
    }

    /**
     * 判断Token是否可用.
     *
     * @param string $token   Token
     * @param int    $user_id 会员ID
     *
     * @return bool
     */
    public function check($token, $user_id){
        $data = self::get($token);
        return $data && $data['user_id'] == $user_id ? true : false;
    }

    /**
     * 删除Token.
     *
     * @param string $token
     *
     * @return bool
     */
   public function delete($token){
       $data = $this->get($token);
       if ($data) {
           $key = $this->getEncryptedToken($token);
           $key = $this->options['prefix'].$key;
           \think\facade\Cache::delete($key);
       }
       return true;
   }

    /**
     * 删除指定用户的所有Token.
     *
     * @param int $user_id
     *
     * @return bool
     */
    public function clear($user_id){
        $userprefix = $this->options['userprefix'].$user_id;
        $key = \think\facade\Cache::get($userprefix);
        if(!empty($key)){
            \think\facade\Cache::delete($key);
        }
        return true;
    }
}